package support.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import support.entity.Pagination;

public class BaseDao<T> extends JdbcTemplate {
	Logger logger = Logger.getLogger(BaseDao.class);
	@Autowired
	protected DataSource dataSource;

	protected List<?> queryForPaginationList(String sql, Object[] objs, RowMapper<? extends T> rowMapper, Pagination pagination) {
		int page = 1;
		if (pagination.getPage() != 0) {
			page = pagination.getPage();
		}
		int pagesize = 30;
		if (pagination.getPagesize() != 0) {
			pagesize = pagination.getPagesize();
		}

		if (pagination.getSortname() != null) {
			sql = sql + " order by " + pagination.getSortname();
			if (pagination.getSortorder() != null) {
				sql = sql + " " + pagination.getSortorder();
			}
		}
		sql = sql + " limit " + pagesize * (page - 1) + "," + pagesize * page;
		// log.info("SQL is:" + sql);
		return query(sql, objs, rowMapper);
	}

	protected int[] batchDeleteById(String sql, String id) {
		if (id.indexOf(",") > 0) {
			String[] idArr = id.split(",");
			List<Object[]> list = new ArrayList<Object[]>();
			for (int i = 0; i < idArr.length; i++) {
				list.add(new Object[] { idArr[i] });
			}
			return batchUpdate(sql, list);
		} else {
			int[] i = { update(sql, id) };
			return i;
		}
	}

	protected List<?> queryWithIn(String sql, String str, RowMapper<? extends T> rowMapper) {
		Object[] args = str.split(",");
		int paramLen = args.length;
		String tmp = "";
		for (int i = 0; i < paramLen; i++) {
			tmp = tmp + "?";
			if (i != paramLen - 1) {
				tmp = tmp + ",";
			}
		}
		sql = sql.replace("?", tmp);
		return query(sql, args, rowMapper);
	}
}
